import React, { useEffect, useRef, useState } from 'react'
import TableSearch from '@/components/TableSearch'
import { columns } from './columns'
import { Input, Table, Modal, message, Select, TablePaginationConfig } from 'antd'
import searchStyle from '@/styles/common.module.less'
import { IFormParams, IUser } from './types'
import ShowInfo from './components/info'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { deleteInfo, remoteList, updateInfo } from '@/api/system/user'
import { userStatus } from './dictionary'
const { confirm } = Modal;

const User = (props: any) => {
    let {isShowSearch = true,params,deptId} = props;
    let initParams = {
        userName: '',
        status: undefined,
        roleName: '',
        deptId:''
    }
    const [loading, setLoading] = useState<boolean>(false);
    const [form, setForm] = useState<IFormParams>({ page: 1, size: 10, ...initParams})
    const [list, setList] = useState<Array<IUser>>([]);
    const [total, setTotal] = useState<number>(0);
    const [rowKeys, setRowKeys] = useState<Array<React.Key>>([]);
    const [info, setInfo] = useState<object>({});
    const [showModal, setShowModal] = useState<boolean>(false);
    const formRef = useRef<IFormParams>({});
    //初始化
    useEffect(() => {
        formRef.current = { ...form };
        search(1);
    }, [])
    //角色变化
    useEffect(()=>{
        if(params){
            let {roleName} = params;
            changeItem(roleName, 'roleName');
            search(1);
        }
    },[params])
    //部门变化
    useEffect(()=>{
        if(deptId){
            changeItem(deptId, 'deptId');
            search(1);
        }
    },[,deptId])
    //搜索
    const search = (async (page?: number): Promise<void> => {
        setLoading(true)
        try {
            setRowKeys([])
            let newForm = { ...form, ...formRef.current }
            if (page) {
                setForm({
                    ...form,
                    page: page
                });
                newForm.page = page;
            };
            let res = await remoteList(newForm);
            let { list, total } = res.data;
            setList(list || [])
            setTotal(total || 0)
        } finally {
            setLoading(false)
        }
    });
    //重置
    const reset = () => {
        for (let k in initParams) {
            formRef.current[k] = initParams[k]
        }
        setForm(formRef.current);
        search();
    }
    //搜索项更新
    const updateForm = (e: React.ChangeEvent<HTMLInputElement>, type: string) => {
        let { value } = e.target;
        changeItem(value, type)
    }
    //选择项目
    const changeItem = (value: string | number, type:string) => {
        setForm({
            ...form,
            [type]: value
        })
        formRef.current[type] = value;
    };
    //选择复选框
    const selectionChange = (values: Array<React.Key>): void => {
        setRowKeys(values)
    }
    //分页切换
    const changePage = (page: TablePaginationConfig) => {
        let { current = 1 } = page;
        changeItem(current, 'page')
        search();
    }
    //修改状态
    const changeStatus = async (info: IUser) => {
        setLoading(true)
        try {
            let { status } = info;
            if (status == 1) {
                info.status = 0
            } else {
                info.status = 1;
            }
            await updateInfo(info);
            message.success('操作成功');
            search();
        } finally {
            setLoading(false)
        }
    }
    //编辑信息
    const showInfo = (info: object = {}) => {
        setInfo(info)
        setShowModal(true);
    }
    //删除信息
    const remove = (info: IUser) => {
        confirm({
            title: '操作提示',
            icon: <ExclamationCircleFilled />,
            content: `确定要删除所选用户?`,
            cancelText: '取消',
            okText: '确定',
            onOk: async () => {
                try {
                    let ids: Array<React.Key | number | undefined> = [];
                    if (info) {
                        ids = [info.userId];
                    } else {
                        rowKeys.map(async item => {
                            ids.push(item);
                        });
                    }
                    await deleteInfo({ ids });
                    message.success('操作成功')
                    search(1)
                } catch (err) {
                    message.error('操作失败')
                }
            }
        });
    }

    return (
        <div className='main_body'>
            {
                isShowSearch && (
                    <TableSearch
                        isSearch={true}
                        isExtra={true}
                        isDelete={!rowKeys.length}
                        search={() => search(1)}
                        reset={() => reset()}
                        add={showInfo}
                        delete={remove}
                    >
                        <>
                            <Input
                                onChange={e => updateForm(e, 'userName')}
                                value={form.userName}
                                className={searchStyle.search_item}
                                placeholder="请输入用户名称" />
                            <Select
                                className={searchStyle.search_item}
                                allowClear
                                value={form.status}
                                placeholder="请选择状态"
                                onChange={e => changeItem(e, 'status')}
                                options={userStatus}
                            />
                        </>
                    </TableSearch>
                )
            }
            <Table
                columns={columns(showInfo, remove, changeStatus)}
                dataSource={list}
                loading={loading}
                rowKey={'userId'}
                pagination={{
                    pageSize: form.size,
                    current: form.page,
                    total: total,
                    showSizeChanger: false,
                    showTotal: () => `共${total} 条`,
                }}
                rowSelection={{
                    selectedRowKeys: rowKeys,
                    onChange: selectionChange,
                }}
                bordered
                scroll={{ x: 800 }}
                onChange={(val) => changePage(val)}
            ></Table>
            {
                showModal && <ShowInfo info={info} close={() => setShowModal(false)} />
            }
        </div>
    )
}

export default User;
